var roleManage = function() {

	var _init = function() {

		

		// 关闭弹框
		$(".modal").on('hidden.bs.modal', function(e) {
			$('.modal .help-block').html(''); // 清空提示
//			$('.modal input').val(''); // 清空 input
		});
		// 添加
		/*$('#btn_new_role').click(function(event) {
			$('#modal_new_role').modal('show');
		});*/
		
		
		var  table_user = $('#table_user');
		table_user
				.dataTable({
					"processing" : true,
					// 开启服务器模式
					serverSide : true,
					"ajax" : {
						url : "/a/user/smsUserList"// 列表查询
					},
					"autoWidth" : false,
					"columns" : [
						  
						{
		                    "width": "20%",//获取用户头像 
		                    "data": "id",
		                    "render": function(data, type, row, meta) {
		                    	var val="--";
		                    	if(data!=null&&data!=''){

		            				$.ajax({
		            					url : '/a/user/mng/imgurl',
		            					type : 'post',
		            					dataType : 'json',
		            					contentType:"application/json; charset=utf-8",
		            					async: false,
		            					data : JSON.stringify({ id: data }),
		            				}).done(function(r) {
		            					if (r.status === '1') { 
		            						if(null==r.data.nickName){
		            							r.data.nickName="";
		            						}
		            						val="<img  width='32px'  src='"+r.data.avatarUrl+"' alt='' /><span>"+r.data.nickName+"</span>";//r.data.属性
		            					} else if (r.status == '2') {
		            					
		            					}
		            				});
		            				return val;
		                    	}else
		                    		return "--";
		                       
		                    }
		                },{
		                    
		                    "data": "mobile"
		                },
							 {     	"width" : "5%",
				                 "sClass": "text-center",
				                 "data": "id",
				                 "render": function (data, type, row, meta) {
				                	 var userIds=$('#userIds').val();
				                	 console.log(userIds);
				                	 if(userIds){
				                		 console.log(row.id);
				                		 if(userIds.indexOf(row.id)>-1){
				                			 return '<input type="checkbox"  class="checkchild"  checked value="' + data + '" />'; 
				                		 }
				                	 }
				                     return '<input type="checkbox"  class="checkchild"  value="' + data + '" />';
				                 },
				              /*   "createdCell": function (td, cellData, rowData, row, col) {
				                	 
				                	 var linkIds=$('#userIds').val();
				                	 console.log(linkIds);
				                	 if(linkIds){
				                		 console.log(rowData.id);
				                		 if(linkIds.indexOf(rowData.id)>-1){
				                			 $(td).parents("tr").addClass("selected");
						                	// $(this).parents("tr").addClass("selected");
				                		 }
				                	 }
				                	
				                     },*/
				                 "bSortable": false
				             }
							
							 ],
					"language" : {
						url: '/assets/pages/Chinese.json'
					},
					"destroy" : true,
					"pageLength" : 9999,
					"bSort":false,
					"order" : [ [ 1, "desc" ] ],
					"columnDefs" : [ {
						"orderable" : false,
						"targets" : [ 0,2 ]
					}],
					"dom" : "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>"
							+ "<t>" + "<'table_b relative'<'col-md-5'i><'col-md-7'>>",
					"fnInitComplete" : function() {
//						$(".totalUser").html(table_user.fnGetNodes().length)
						
					}
				});
		
		
		
		
		var  sms_table = $('#sms_table');
		sms_table
				.dataTable({
					"processing" : true,
					// 开启服务器模式
					serverSide : true,
					"ajax" : {
						url : "/a/sms/smsList"// 列表查询
					},
					"autoWidth" : true,
					"columns" : [
						  
						{
							  "data": "content",
							  "width": "50%"
		                  
		                },{
		                    
		                    "data": "peoples"
		                },{
		                    
		                    "data": "nums"
		                },{
		                    
		                    "data": "createDate",
		                    "render": function(data, type, row, meta) {
	                            return moment(data).format('YYYY-MM-DD HH:mm');
	                        }
		                },
							
							 ],
					"language" : {
						url: '/assets/pages/Chinese.json'
					},
					"destroy" : true,
					"pageLength" : 10,
					"order" : [ [ 3, "desc" ] ],
					"columnDefs" : [ {
						/*"orderable" : false,
						"targets" : [ 0,2 ]*/
					}],
					"dom" : "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>"
							+ "<t>" + "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
					"fnInitComplete" : function() {
					}
				});
		
		
		
		
		
		 $("#xzsl").on("click",function(e){
			 window.location.href='/assets/pages/number.txt';
		 })		
		// 确定添加
		$("#modal_sure_new").on("click",function(e){

			let phone=$("#phone").val();
			let content=$("#content").val();
			let startTime=$("#startTime").val();
		    let smsCount=$('.smsCount').html();
		    let fsts=$('.fsts').html();
		    if(Number(fsts)>Number(smsCount)){
		    	mdTool.showMessageForHelpBlock("短信余额不足，请充值！")
				return;
		    }
			if(!mdTool.validate(phone, 'require')) {
				mdTool.showMessageForHelpBlock("手机号码不能为空！")
				return;
			}
			if(!mdTool.validate(content, 'require')) {
				mdTool.showMessageForHelpBlock("发送内容不能为空！")
				return;
			}
			if(!$("input[name='isSmsReadLicense']").is(':checked')){
				mdTool.showMessageForHelpBlock("请先阅读《短信发送须知》！")
				return;
			}
			let sendTime;
			if(startTime){
				sendTime=  (new Date(startTime)).getTime()
			}
			$('#modal_sure_new').attr("disabled",true);
			var param = {"phone": phone,"content":content,"sendTime":sendTime};
			$.ajax({
				url: '/a/sms/sendSms',
				type: "POST",
				dataType: 'json',
				contentType: "application/json; charset=utf-8",
				data: JSON.stringify(param),
			}).done(function(data) {
				if(data.status === '1') {
					console.log('发送成功！');
					$('.help-block').html("发送成功！"); 
					$(".help-block").attr("style","color:green;");
					$(".smsCount").html(Number(smsCount)-Number(fsts))
					$('#modal_sure_new').attr("disabled",false);
					 setTimeout(function(){$('.help-block').html("");},5000);//5秒后执行该方法
				} else if(data.status === '2') {
					mdTool.showMessageForHelpBlock(data.message);
					$('#modal_sure_new').attr("disabled",false);

				}
			}).fail(function(data) {
				$('#modal_sure_new').attr("disabled",false);

			});
			
			
			
		})


		
		  $('.user_query').click(function(event){
		  var like =   $("#select_user input[name='like']").val();
		  var param={"like":like};
		  $('#table_user').DataTable().search(JSON.stringify(param)  ).draw();
		/*  $(".totalUser").html( $('#table_user').dataTable().fnGetNodes().length)*/
		  
		});
		
		$('#table_user .select-all').click(function() {
			if ($(this).is(':checked')){
			 $("#table_user :checkbox").prop("checked", true);
			 $("#table_user tbody tr").addClass("selected");
			}
			else {
			 $("#table_user :checkbox").prop("checked", false);
			 $("#table_user tbody tr").removeClass("selected");

			}
			});
		
		$("#table_user").on('click', '.checkchild', function(event) {
				 
		    /*  var check = $(this).prop("checked");
		      $(this).prop("checked", !check);*/
				 $(this).parents("tr").toggleClass("selected");
				});
		/*  
		$("#table_user .checkchild").click(function () {
			alert("fdsaf")
			

		});*/

		$('.btn_select').on('click', function() { 
			var data=$('#table_user').DataTable().rows('.selected').data();
			var length=data.length;
			$(".jsrs").html(length);
			var ids="";
			let phone="";
			for(var i=0;i<length;i++){
				if(i==0){
					ids=data[i].id;
					phone=data[i].mobile;
				}else{
					ids+=","+data[i].id;
					phone+=","+data[i].mobile;
				}
				
			}
	        $('#userIds').val(ids);
	        $("#phone").val(phone);
			$('#select_user').modal('hide');
			  $("#phone").trigger('change');

	}); 
		
     $(".import").click(function(){
            $("#filename").trigger('click');
          /*  $.ajax({
		        url: 'C:\Users\zhiwei\Desktop\11.txt',
		        dataType: 'text',
		        success: function(data) {
		            alert(data);
		        }
		    });*/
           
        });
     
     $("#filename").change(function(){
     	var files = $('#filename').prop('files');//获取到文件列表
     	if(files.length == 0){
//     	  alert('请选择文件');
     	  return;
     	}else{
     		if(files[0].name.indexOf('.txt')==-1){
     			  $('.help-import').html("请选择txt文件！"); 
     			   $(".help-import").attr("style","color:red;");
     			return;
     		}
     	  var reader = new FileReader();//新建一个FileReader
     	  reader.readAsText(files[0], "gb2312");//读取文件 gb2312  UTF-8
     	  reader.onload = function(evt){ //读取完文件之、后会回来这里
     	    var fileString = evt.target.result;
     	    $("#phone").val(fileString);
     	   $("#phone").trigger('change');
     	   $('.help-import').html("导入成功！"); 
		   $(".help-import").attr("style","color:green;");
		   setTimeout(function(){$('.help-import').html("");},5000);//5秒后执行该方法
     	  }
     	}
     });
     
     $("#phone").change(function(){
    	 	var content = $('#content').val();
           	var phone = $('#phone').val();
           	var myArray=phone.split(",") ;
           	var length=content.length+5;//加上签名
            var num=Math.ceil(length/67)*myArray.length　
            $('.fsts').html(num);
      });
     
     
     $("#content").change(function(){
       	var content = $('#content').val();
       	var phone = $('#phone').val();
       	var myArray=phone.split(",") ;
       	var length=content.length+5;//加上签名
        var num=Math.ceil(length/67)*myArray.length　
        $('.fsts').html(num);
       });
     
     
     
 	$("#sava_users").click(function() {
	    var _data = $("#filename").val();
	  
		if (!mdTool.validate(_data, 'require')) {
			mdTool.showMessageForHelpBlock("请选择一个文件！")
			return;
		}if (_data.indexOf('.txt')<0) {
			mdTool.showMessageForHelpBlock("请选择.txt格式文件！")
			return;
		}
	else {
		$('.help-block').html(""); 
		$("#form_user_add").submit();
					
			
		
		
	}});
 	
 	
 	 $(".smsHistory").on("click",function(e){
		 window.location.href='/p/sms/send/smsList';

	 })	
	 
 	 $(".smsBuy").on("click",function(e){
		 window.location.href='/p/sms/buy';
	 })	
	 $(".historyback").on("click",function(e){
		 //window.history.back();
		 window.location.href='/p/sms/send';

	 })	

	 
	 $(".smsBuy").on("click",function(e){
		 window.location.href='/p/sms/buy';
	 })		
		
	 $(".readTipButton").on("click",function(e){
		 $("input[name='isSmsReadLicense']").prop("checked",true)
	 })		
	}

	return {
		init : function() {
			_init();
		}
	};

}();



$(function() {
	roleManage.init();
	
	
	var lm = $("input[name='object']:checked").parent("label").index();
	console.log(lm);
	$(".objectCon").eq(lm).show();
	
	$(".object label").click(function(){
		var ln = $(this).index();
		$(".objectCon").eq(ln).show().siblings(".objectCon").hide();
	});
	
	
	
});